package com.fastjrun.security.authentication;

import com.fastjrun.apiworld.vo.ResultModel;
import com.fastjrun.apiworld.helper.ResultHelper;
import com.fastjrun.security.properties.SecurityProperties;
import com.fastjrun.share.demo.security.vo.LoginUserVO;
import com.fastjrun.share.demo.security.vo.UserDetailsVO;
import com.fastjrun.utils.JacksonUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.SavedRequestAwareAuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

@Component("customAuthenticationSuccessHandler")
//public class CustomAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
public class CustomAuthenticationSuccessHandler extends SavedRequestAwareAuthenticationSuccessHandler {
    Logger logger = LoggerFactory.getLogger(getClass());
    @Autowired
    SecurityProperties securityProperties;

    @Autowired(required = false) // 容器中可以不需要有接口的实现，如果有则自动注入
    AuthenticationSuccessListener authenticationSuccessListener;

    @Override
    public void onAuthenticationSuccess(HttpServletRequest request,
                                        HttpServletResponse response, Authentication authentication) throws IOException {

        LoginUserVO loginUserVO = new LoginUserVO();
        if (authenticationSuccessListener != null) {
            // 当认证之后 ，调用此监听，进行后续处理，比如加载用户权限菜单
            authenticationSuccessListener.successListener(request, response, authentication);
        }
        UserDetailsVO userDetails = (UserDetailsVO) (authentication.getPrincipal());
        loginUserVO.setUserId(userDetails.getSysUser().getId());
        loginUserVO.setUsername(userDetails.getSysUser().getUsername());
        loginUserVO.setToken(request.getSession().getId());
        ResultModel<LoginUserVO> result = ResultHelper.ok(loginUserVO);
        response.setContentType("application/json;charset=UTF-8");
        response.getWriter().write(JacksonUtils.toJSon(result));
    }
}
